package org.altervista.cp.microkernel.install;

import java.io.Serializable;
import java.net.URL;
import java.sql.Connection;
import java.sql.DatabaseMetaData;

import javax.sql.DataSource;

import org.altervista.cp.microkernel.install.sql.SQLScriptExcecutor;
import org.altervista.cp.microkernel.log.Log;
import org.altervista.cp.microkernel.util.ClassLoaderUtils;

public final class KernelInstaller extends Installer implements Serializable {

	private static final Log log = new Log(KernelInstaller.class);

	private static final long serialVersionUID = 1L;

	public KernelInstaller(InstallManager im) {
		super(im);
	}

	public byte getMajorVersion() {
		return 1;
	}

	public byte getMinorVersion() {
		return 0;
	}

	public void install(DataSource ds) {
		try {
			log.info("Starting creation of the kernel database");
			Connection c = ds.getConnection();
			DatabaseMetaData dbmd = c.getMetaData();
			String dbName = dbmd.getDatabaseProductName().toLowerCase()
					.replace(' ', '_');
			String dbVersion = dbmd.getDatabaseMajorVersion() + "."
					+ dbmd.getDatabaseMinorVersion();
			c.close();
			String scriptDirPath = SQLScriptExcecutor.class.getPackage()
					.getName().replaceAll("\\.", "/")
					+ "/" + dbName;
			URL scriptURL = ClassLoaderUtils.lookupResource(scriptDirPath
					+ "/install_kernel.sql");
			if (scriptURL == null) {
				scriptURL = ClassLoaderUtils.lookupResource(scriptDirPath + "_"
						+ dbVersion + "/install_kernel.sql",
						KernelInstaller.class);
				if (scriptURL == null) {
					throw new InstallationException(
							"The kernel installation script cannot be found");
				}
			}
			SQLScriptExcecutor.execute(scriptURL.getPath(), ds);
			log.info("The kernel database has been created");
		} catch (Exception e) {
			throw new InstallationException(e);
		}
	}

	public void uninstall(DataSource ds) {
	}

	public String getName() {
		return "KernelInstaller";
	}

}
